import os
os.chdir('F:/AI_BASIC/ai_-basic/AI_Basic_lab/RegrassionAndPredict')
re_path = 'F:/AI_BASIC/ai_-basic/AI_Basic_lab/RegrassionAndPredict/9multi_variable_regression.py'

import logging
logger = logging.getLogger('multiregrassion')
logger.setLevel(logging.INFO)
addHandler = logging.FileHandler(re_path + '.log')
formatter = logging.Formatter('%(asctime)s --- %(name)s --- %(levelname)s --- %(message)s')
addHandler.setFormatter(formatter)
logger.addHandler(addHandler)
logger.info('Third testing log')


import pandas as pd
# 二手房数据
house_price_df = pd.read_csv('bj_house_information.csv')

#册除一些不重要的列
to_drop = ['Id', '楼层', '小区名称', '地点', '楼龄', '户型', '朝向']
house_price_df_clean = house_price_df.drop(to_drop, axis=1)
# 显示列名
print(house_price_df_clean.columns)
print(house_price_df_clean.head())


# 重新摆放列位置
columns = ['房屋总价', '建筑面积', '区域','电梯', '装修', ]
house_price_df_clean = pd.DataFrame(house_price_df_clean, columns = columns)
print(house_price_df_clean.head())

lianjia_total_num = house_price_df_clean['建筑面积'].count()
print('房价数据集总数量为: ' + str(lianjia_total_num))

#数据清洗
df = house_price_df_clean
df['房屋单价'] = df['房屋总价']/df['建筑面积']
# 对汇总数据再次清洗
df.dropna(how='any')
df.drop_duplicates(keep='first', inplace=True)
# 一些别墅的房屋单价有异常，删选价格少于25万一平的
df = df.loc[df['房屋单价']<25]


#####################################################################

# 先根据建筑面积和房屋总价训练模型（一元线性回归）
from sklearn.linear_model import LinearRegression
import numpy as np
# 汉字到数字的映射字典
loc_map = {'东城':1, '西城':2, '朝阳':3, '海淀':4, '丰台':5, '石景山':6, '通州':7, '昌平':8, '大兴':9, '亦庄开发区':10,
           '顺义':11, '房山':12, '门头沟':13, '平谷':14, '怀柔':15, '密云':16, '延庆':17, '燕郊':18, '香河':19}
renovation_map = {'简装':0, '精装':1, '其它':2}
elevator_map = {'有电梯':1, '无电梯':0}

# 数据集映射和清洗
df['区域'] = df['区域'].map(loc_map)
df['装修'] = df['装修'].map(renovation_map)
df['电梯'] = df['电梯'].map(elevator_map)
df = df.dropna(how='any')
print(df.head())

# ### 多特征模型训练（多元线性回归）
# cols = ['建筑面积', '区域','户型']
cols = ['建筑面积','区域', '装修', '电梯']
x = df[cols]
print(x.head())

y = df['房屋总价']
print(y.head())

print(type(x))
print(type(y))

# 使用train_test_split进行交叉验证
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=12)
print("训练集大小 " + str(x_train.shape) + str(y_train.shape))
print("测试集大小 " + str(x_test.shape) + str(y_test.shape))

# 模型训练
linear = LinearRegression()
model = linear.fit(x_train,y_train)
# print(model.intercept_, model.coef_)

# 模型性能评分
price_end = model.predict(x_test)
score = model.score(x_test,y_test)
print("模型得分：", score)# 一般模型在0.6以上就表现的不错


# 线性回归可视化(数据拟合)
import matplotlib.pyplot as plt
linear_p = model.predict(x)
plt.figure(figsize=(12,6))
plt.rc('font', family='SimHei', size=13)

plt.scatter(x['建筑面积'],y, s = 1, c="g")
plt.scatter(x['建筑面积'],linear_p, s = 1, c="b")


# 汉字到数字的映射字典
# loc_map = {'东城':1, '西城':2, '朝阳':3, '海淀':4, '丰台':5, '石景山':6, '通州':7, '昌平':8, '大兴':9, '亦庄开发区':10,
#            '顺义':11, '房山':12, '门头沟':13, '平谷':14, '怀柔':15, '密云':16, '延庆':17, '燕郊':18, '香河':19}
# renovation_map = {'简装':0, '精装':1, '其它':2}
# elevator_map = {'有电梯':1, '无电梯':0}
# cols = ['建筑面积','区域', '装修', '电梯']
# 假设我要买一套房子，房子面积120平米，区域东城，精装，有电梯
my_house = [120,1,1,1]
my_house = np.array(my_house).reshape(-1,1).T
my_house_price = model.predict(my_house)
print(my_house_price)# 预测价格
plt.scatter([120],my_house_price, s = 50, c="r")

plt.xlabel("建筑面积")
plt.ylabel("房屋总价")
plt.show()



